<!--  
 * 角色管理右侧抽屉新增编辑内容
 * @author: 
 * @since: 2022-05-06
 * index.vue
-->
<template>
    <div class="offsideDrawer">
        <el-drawer v-model="isShowDrawer" title="" :before-close="closedDrawer">
            <template #title>
                <div class="drawer-title">
                    <div class="title-icon"></div>
                    <div class="title-text">
                        <span>{{ drawer.title }}</span>
                        <span>角色</span>
                    </div>
                </div>
            </template>
            <template #default>
                <el-form class="drawer-content" :model="form" :rules="rules" ref="validateform">
                    <el-form-item label="角色名称：" prop="rolename" class="rolename">
                        <inputCustom :model="form.rolename" placeholder="请输入角色名称" :maxLength="64" @inputEvent="inputRoleName"></inputCustom>
                    </el-form-item>
                    <el-form-item label="角色描述：" prop="rolenode">
                        <el-input v-model="form.rolenode" type="textarea" placeholder="请输入角色描述" :rows="12" />
                    </el-form-item>
                    <el-form-item label="角色权限设置：" :required="true" class="noRules">
                        <el-tree :data="state.allMenuList" show-checkbox node-key="id" :default-checked-keys="[]" :props="defaultProps" @check-change="selectTree" default-expand-all ref="tree" check-on-click-node />
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button type="primary" size="mini" style="width: 100px" @click="save">提交</el-button>
                    <el-button size="mini" style="width: 100px" @click="closedDrawer">取消</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup>
import { reactive, ref, defineProps, defineEmits, onMounted, watch, inject } from 'vue'
import { getAllMenuList, addRole, editRole, getRoleMenuPermission } from '@/api/interface/role.js'
import { successHandle, recursiveId } from '@/utils/common.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
const router = useRouter();
const props = defineProps({
    isShowDrawer: {//是否展开角色抽屉
        type: Boolean,
        default: false
    },
    roleId: [String],
    data: {//row数据
        type: Object,
        default: () => {

        }
    }
})

const emits = defineEmits(['close', 'refresh'])
const reload = inject('reload')


const state = reactive({
    allMenuList: [],//所有菜单数据
    selectAllIdList: [],//选中的所有menuIdList

})
const drawer = reactive({
    title: '新增'
})
const defaultProps = {
    children: 'childresource',
    label: 'menucn',
}

//新增编辑 form
const form = reactive({
    rolename: '',//角色名称
    rolenode: '',//角色描述
})

//表单验证 
const rules = {
    rolename: [{ required: true, message: '必填项', trigger: 'blur' }],
};

//表单元素
const validateform = ref(null);

//树 dom
const tree = ref(null);

onMounted(() => {
    getAllMenu();
})

//获取所有的菜单数据
const getAllMenu = () => {
    getAllMenuList().then(res => {
        const { status, data } = res
        if (status === 200) {
            state.allMenuList = data;
        }
    })
}

//获取当前角色菜单的权限
const getCurrentRoleMenuPermission = async (id) => {
    await getRoleMenuPermission({ roleId: id }).then(res => {
        const { status, data } = res
        if (status === 200) {
            const selectArr = recursiveId(data);
            selectArr.forEach(item => {
                tree.value.setChecked(item, true, false);
            });
        }
    })
}

//选择角色权限配置数据
const selectTree = (data, checked) => {
    state.selectAllIdList = tree.value.getCheckedKeys().concat(tree.value.getHalfCheckedKeys())
}


//角色名称输入事件
const inputRoleName = (text) => {
    form.rolename = text
}

//关闭抽屉 清空数据
const closedDrawer = () => {
    validateform.value.resetFields()
    emits('close')
    tree.value.getCheckedNodes().some(item => {
        tree.value.setChecked(item.id, false, true)
    })
    for (let key in form) {
        form[key] = ''
    }
    drawer.title = '新增'
}
//新增角色调用接口
const postAddRole = (data) => {
    addRole(data).then(res => {
        successHandle(res)
        closedDrawer();
        emits('refresh')
    })
}

//修改角色调用接口
const putEditRole = (params) => {
    editRole(params).then(async res => {
        successHandle(res)
        closedDrawer()
        emits('refresh')
        if (res.status === 200) {
            reload()
            await store.dispatch('user/getMenuList')
            await store.dispatch('routes/setAllRoutes').then((res) => {
                res.forEach((item) => {
                    router.addRoute(item)
                })
            })

        }
    })
}

//保存
const save = () => {
    validateform.value.validate((valid) => {
        if (valid) {
            if (state.selectAllIdList.length === 0) {
                ElMessage({
                    message: '角色权限设置必选项',
                    type: 'warning',
                })
            } else {
                if (props.roleId) {//修改
                    console.log('修改');
                    const params = {
                        role: {
                            id: props.roleId,
                            rolename: form.rolename,
                            rolenode: form.rolenode
                        },
                        resourceId: state.selectAllIdList
                    }
                    putEditRole(params)
                    emits('close')

                } else {//新增
                    console.log('没有id，新增');
                    const params = {
                        role: {
                            rolename: form.rolename,
                            rolenode: form.rolenode
                        },
                        resourceId: state.selectAllIdList
                    }
                    postAddRole(params);
                    emits('close')
                }
            }
        } else {
            console.log('没通过验证');
        }
    });
}

//watch监听
watch(() => props.roleId, (val) => {
    if (val) {
        for (let key in form) {
            form[key] = props.data[key]
        }
        drawer.title = "编辑"
        getCurrentRoleMenuPermission(props.roleId)
    }


})



</script>
<style lang="scss" scoped>
.el-form-item__content {
    width: 100%;
}

.rolename {
    margin-bottom: 0;

    :deep(.el-form-item__error) {
        top: 90%;
    }
}
</style>
